package com.xjysx.xiaochetong.moudle;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import android.serialport.SerialPortConstants;
import android.serialport.SerialPortEvent;
import android.serialport.SerialPortUtil;

import com.serialportlibrary.util.LogUtil;
import com.xjysx.xiaochetong.R;
import com.xjysx.xiaochetong.base.BaseActivity;
import com.xjysx.xiaochetong.entities.EndCountDownEvent;
import com.xjysx.xiaochetong.network.BaseBean;
import com.xjysx.xiaochetong.network.BaseObserver;
import com.xjysx.xiaochetong.network.Network;
import com.xjysx.xiaochetong.util.PollingUtil;
import com.xjysx.xiaochetong.util.SignatureUtil;
import com.xjysx.xiaochetong.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.xjysx.xiaochetong.network.Network.GET_QRCODE;

@RuntimePermissions
public class SplashActivity extends BaseActivity {

    @BindView(R.id.iv_splash)
    ImageView imageView;
    @BindView(R.id.tv_test)
    TextView tvTest;

    private boolean isFirstOpen = true;

    private MyHandler handler = new MyHandler(this);
    private PollingUtil pollingUtil;
    private Runnable runnable_heart;


    private static class MyHandler extends Handler {

        WeakReference<SplashActivity> weakReference;

        public MyHandler(SplashActivity splashActivity) {
            weakReference = new WeakReference<>(splashActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                Intent intent = new Intent(weakReference.get(), MainActivity.class);
                weakReference.get().startActivity(intent);
            }
//            }
            weakReference.get().finish();
        }
    }


    private BaseObserver<Object> observer = new BaseObserver<Object>() {

        @Override
        public void onSuccess(Object bean) {
            dismissDialog();
            String qrcode_sn = ((Map) bean).get("qrcode_sn").toString();
            Intent intent = new Intent(getContext(), QrCodeActivity.class);
            intent.putExtra("qrcode_sn", qrcode_sn);
            startActivity(intent);
        }

        @Override
        public void onError(int code, String message, BaseBean baseBean) {
            dismissDialog();
//            ToastUtil.showToast(getContext(), message);
        }

        @Override
        public void networkError(Throwable e) {
            dismissDialog();
//            ToastUtil.showToast(getContext(), getContext().getResources().getString(R.string.network_error));
        }
    };

    @Override
    protected void loadLayout() {
        setContentView(R.layout.activity_splash);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    public void initPresenter() {
    }


    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            if (preferences.getString("sn", "").length() == 0) {
                EventBus.getDefault().post(new SendHeartEvent());
            } else {
                timer.cancel();
            }
        }
    };

    @Override
    protected void initialize(Bundle savedInstanceState) {
        super.initialize(savedInstanceState);
        EventBus.getDefault().register(this);
        preferences.edit().putString("sn", "").apply();
        preferences.edit().putBoolean("started",false).apply();
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        SerialPortUtil.openSrialPort(getApplicationContext());
        preferences.edit().putBoolean("started", false).apply();
        timer.schedule(task, 0, 1000);
        byte[] data = new byte[]{123, -73, 13, 1, 1, 75, 66, 89, 45, 78, 48, 48, 48, 49, 65, -38, -48};
        pollingUtil = new PollingUtil(new Handler(getMainLooper()));
        runnable_heart = new Runnable() {
            @Override
            public void run() {
                SerialPortUtil.sendSerialPortByte(SerialPortConstants.HEART);
            }
        };
//        receiveSN(new SerialPortEvent(data, data[3]));
        //每2秒请求一次接口
//        SerialPortUtil.sendEvent();
        if(!getIntent().getBooleanExtra("restart",false)) {
            pollingUtil.startPolling(runnable_heart, 2000, true);
        }
    }

    @OnClick(R.id.iv_splash)
    public void onViewClicked() {
        showProgressDialog();
        Map<String, String> map = new HashMap<>();
        map.put("chipcode", preferences.getString("sn", ""));
        String passWord = SignatureUtil.getPassword();
        map.put("password", passWord);
//        ToastUtil.showToast(getContext(),map.toString());
        Network.getQrCode().getQrCode(GET_QRCODE, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void sendHeart(SendHeartEvent event){
        SerialPortUtil.sendSerialPortByte(SerialPortConstants.GETSN);
//        preferences.edit().putString("sn", "KBY-N0001A-F628C3F5001697").apply();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveSN(SerialPortEvent event) {
        byte[] data = event.data;
        int cmd = event.cmd;
        //body  参数位+数据
        if (cmd == 1) {
            byte[] body = new byte[data.length - 7];
            tvTest.setText("sn:" + SerialPortConstants.byteArrayToHex(event.data));
            for (int i = 0; i < data.length - 7; i++) {
                body[i] = data[i + 5];
            }
            String sn = SerialPortConstants.byteArrayToString(body);
            preferences.edit().putString("sn", sn).apply();

        }
    }


    @Override
    protected int getTranslucentColor() {
        return R.color.transparent;
    }


    //=======================动态权限的申请===========================================================<
    @NeedsPermission({
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void startWelcomeGuideActivity() {
    }

    /**
     * 为什么要获取这个权限给用户的说明
     *
     * @param request
     */
    @OnShowRationale({
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("有部分权限需要你的授权")
//                .setPositiveButton(R.string.imtrue, (dialog, button) -> request.proceed())
//                .setNegativeButton(R.string.cancel, (dialog, button) -> request.cancel())
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show()
        ;
    }

    /**
     * 如果用户不授予权限调用的方法
     */
    @OnPermissionDenied({
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForCamera() {
        showPermissionDenied();
    }

    public void showPermissionDenied() {
        new AlertDialog.Builder(this)
                .setTitle("权限说明")
                .setCancelable(false)
                .setMessage("本应用需要部分必要的权限，如果不授予可能会影响正常使用！")
                .setNegativeButton("退出应用", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setPositiveButton("赋予权限", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SplashActivityPermissionsDispatcher.startWelcomeGuideActivityWithCheck(SplashActivity.this);
                    }
                })
                .create().show();
    }

    /**
     * 如果用户选择了让设备“不再询问”，而调用的方法
     */
    @OnNeverAskAgain({
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForCamera() {
        Toast.makeText(this, "不再询问授权权限！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SplashActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

//=======================动态权限的申请===========================================================>

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onBackPressed() {
        pollingUtil.endPolling(runnable_heart);
        finish();
    }
    private boolean isExites() {
        if (!isTaskRoot()) {
            finish();
            return true;
        }
        return false;
    }
}
